package bepviet.android.ui;

import java.util.ArrayList;

import bepviet.android.engine.DataAdapter;
import bepviet.android.engine.DataFoodAdapter;
import bepviet.android.engine.MainMenu;
import bepviet.android.engine.WebServiceAdapter;
import bepviet.android.properties.StringInPair;
import bepviet.android.properties.User;
import bepviet.android.ui.PreparedMail;
import bepviet.android.engine.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class TextContent extends Activity {

	private TextView text1, text2, text3, txtback, txttitle, clickmonan,txtviewer,
			clicknguyenlieu, clickthuchien,txtdanhgia;
	private String s1, s2, s3, s4, contentmail;
	private String ThucHien, GioiThieu = "", NguyenLieuChuanBi, LoaiMonAn = "", XuatXu = "",
			TenMonAn, viewer;
	private float rating,newrating;
	private LinearLayout layoutmain, layoutcontent;
	private ImageView imgView, imgmail, imgfavorite,imgface;
	private RatingBar ratingbar;
	private byte[] blob;
	private StringInPair item;
	private WebServiceAdapter serviceAdapter;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.text_content);

		LayoutInflater inflater2 = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = inflater2.inflate(R.layout.text_intro, null);

		ratingbar = (RatingBar)findViewById(R.id.ratingbar);
		layoutcontent = (LinearLayout) findViewById(R.id.layoutcontent2);
		clickmonan = (TextView) findViewById(R.id.click_monan);
		clicknguyenlieu = (TextView) findViewById(R.id.click_nguyenlieu);
		clickthuchien = (TextView) findViewById(R.id.click_thuchien);
		text1 = (TextView) view.findViewById(R.id.txtIntro);
		text2 = new TextView(this);
		text3 = new TextView(this);
		txtdanhgia = (TextView)findViewById(R.id.txtdanhgia);
		txtviewer = (TextView)findViewById(R.id.txtviewer);
		txtback = (TextView) findViewById(R.id.txtback_content);
		txttitle = (TextView) findViewById(R.id.txttitle_content);
		imgfavorite = (ImageView) findViewById(R.id.iconfavorite);
		imgmail = (ImageView) findViewById(R.id.iconmail);
		imgface = (ImageView) findViewById(R.id.iconface);
		imgView = (ImageView) view.findViewById(R.id.imageview);

		Intent intent = getIntent();
		final Bundle bundle = intent.getExtras();
		
		//Load tu mot Tao moi mon an hoac ListMonAn
		int SELECT_LBR = bundle.getInt("SELECT");
		if (SELECT_LBR == 1)
			Query1(bundle);
		else
			 Query2(bundle);	
		

			TenMonAn = bundle.getString("Ten");
		s1 = " -Tên Món Ăn : " + TenMonAn + "\n -Loại Món Ăn : " + LoaiMonAn
				+ "\n -Xuất Xứ : " + XuatXu + "\n -Giới Thiệu : \n" + GioiThieu;
		s2 = " NGUYÊN LIỆU CHUẨN BỊ :\n" + NguyenLieuChuanBi;
		s3 = " THỰC HIỆN :\n" + ThucHien;
		contentmail = s1 + "\n\n" + s2 + "\n\n" + s3 + "\n\n" + s4;

		text2.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		text3.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		text1.setPadding(5, 5, 5, 5);
		text1.setTextSize(17f);
		text1.setTextColor(0xFF800000);
		text2.setPadding(5, 5, 5, 5);
		text2.setTextSize(17f);
		text2.setTextColor(0xFF800000);
		text3.setPadding(5, 5, 5, 5);
		text3.setTextSize(17f);
		text3.setTextColor(0xFF800000);

		text2.setMovementMethod(new ScrollingMovementMethod().getInstance());
		text3.setMovementMethod(new ScrollingMovementMethod().getInstance());

		imgView.setImageDrawable(convertBlobToBitmap(blob));
		imgView.setPadding(10, 10, 10, 10);

		// set text cho tat ca Textview
		text1.setText(s1);
		text2.setText(s2);
		text3.setText(s3);
		txtviewer.setText("("+viewer+" view)");
		ratingbar.setRating(rating);
		txttitle.setText(TenMonAn);
		layoutcontent.addView(view);
		clickmonan.clearAnimation();
		clicknguyenlieu.clearAnimation();
		clickthuchien.clearAnimation();

		
		ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				newrating = rating;
				
			}
		});
		
		// binh chon rating cho mon an
		txtdanhgia.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				serviceAdapter = new WebServiceAdapter("Rating");
				float rating1 = (rating + newrating)/2 ;
//				String temp = serviceAdapter.Rating(User.username, bundle.getInt("Ma"), rating1);
//				if(temp.equals("true")){
//					Toast.makeText(TextContent.this, "add 1 rating", Toast.LENGTH_LONG).show();
//				}
//				else
//					Toast.makeText(TextContent.this, "Fail", Toast.LENGTH_LONG).show();
				Toast.makeText(TextContent.this, String.valueOf(rating1), Toast.LENGTH_LONG).show();
			}
		});
		
		
		clickmonan.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				layoutcontent.removeAllViews();
				layoutcontent.addView(view);
				if (clickmonan.isClickable()) {
					clickmonan.setBackgroundColor(0xFFFFFFFF);
					clicknguyenlieu.setBackgroundResource(R.drawable.stock);
					clickthuchien.setBackgroundResource(R.drawable.stock);
				}
			}
		});

		clicknguyenlieu.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				layoutcontent.removeAllViews();
				layoutcontent.addView(text2);
				if (clicknguyenlieu.isClickable()) {
					clicknguyenlieu.setBackgroundColor(0xFFFFFFFF);
					clickmonan.setBackgroundResource(R.drawable.stock);
					clickthuchien.setBackgroundResource(R.drawable.stock);
				}
			}
		});

		clickthuchien.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				layoutcontent.removeAllViews();
				layoutcontent.addView(text3);
				if (clickthuchien.isClickable()) {
					clickthuchien.setBackgroundColor(0xFFFFFFFF);
					clickmonan.setBackgroundResource(R.drawable.stock);
					clicknguyenlieu.setBackgroundResource(R.drawable.stock);
				}
			}
		});

		txtback.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		imgmail.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(TextContent.this, PreparedMail.class);
				Bundle bundle = new Bundle();
				bundle.putString("contentmail", contentmail);
				intent.putExtras(bundle);
				startActivity(intent);

			}
		});

		imgfavorite.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				DataFoodAdapter dataAdapter = new DataFoodAdapter(
						TextContent.this);
				final SQLiteDatabase db = dataAdapter.OpenPath();
				ContentValues value = new ContentValues();
				value.put("TenMonAn", item.getLoai());
				value.put("MaMonAn", item.getMa());
				dataAdapter.Insert(db, value, "YeuThich");
				dataAdapter.close();

			}
		});
		
		imgface.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Intent intent = new Intent(Intent.ACTION_SEND);
				intent.setType("text/plain");
				intent.putExtra(Intent.EXTRA_SUBJECT, "Sharing");
				intent.putExtra(Intent.EXTRA_TEXT,contentmail);
				startActivity(Intent.createChooser(intent,"Select an action for sharing"));
				
			}
		});

	}
	
	// =================================================================================
	
	private void Query1(Bundle bundle) {
		
		DataAdapter dataAdapter = new DataAdapter(this);
		Cursor c;

		dataAdapter.OpenDataBase(); // open connect database

		try {
			c = dataAdapter.QueryData("Select * from MonAn where MaMonAn = '"
					+ bundle.getInt("Ma") + "'");
			if (c != null) {
				if (c.moveToFirst()) {
					do {
						blob = c.getBlob(c.getColumnIndex("HinhAnh"));
						ThucHien = c.getString(c.getColumnIndex("ThucHien"));
						GioiThieu = c.getString(c.getColumnIndex("GioiThieu"));
						NguyenLieuChuanBi = c.getString(c
								.getColumnIndex("NguyenLieuChuanBi"));
						item = new StringInPair(c.getString(c
								.getColumnIndex("TenMonAn")), c.getInt(c
								.getColumnIndex("MaMonAn")));
						viewer = c.getString(c.getColumnIndex("view"));
						rating = Float.parseFloat(c.getString(c.getColumnIndex("rating")));
					} while (c.moveToNext());
				}
			}
		} catch (Exception ex) {
		}

		try {
			c = dataAdapter.QueryData("Select * from LoaiMonAn where MaLoai = "
					+ "(Select MaLoai from MonAn where MaMonAn = '"
					+ bundle.getInt("Ma") + "')");
			if (c != null) {
				if (c.moveToFirst()) {
					do {
						LoaiMonAn = c.getString(c.getColumnIndex("TenLoai"));
					} while (c.moveToNext());
				}
			}
		} catch (Exception ex) {
		}

		try {
			c = dataAdapter.QueryData("Select * from XuatXu where MaXuatXu = "
					+ "(Select MaXuatXu from MonAn where MaMonAn = '"
					+ bundle.getInt("Ma") + "')");
			if (c != null) {
				if (c.moveToFirst()) {
					do {
						XuatXu = c.getString(c.getColumnIndex("VungXuatXu"));
					} while (c.moveToNext());
				}
			}
		} catch (Exception ex) {
		}
		ArrayList<String> NguyenLieu = null;
		try {
			c = dataAdapter
					.QueryData(" Select  TenNguyenLieu from NguyenLieu N "
							+ "Join MonAn_NguyenLieu MN on MN.MaNguyenLieu = N.MaNguyenLieu "
							+ "Join MonAn M on M.MaMonAn = MN.MaMonAn and M.MaMonAn = '"
							+ bundle.getInt("Ma")
							+ "' "
							+ "Group by TenNguyenLieu Having count(distinct M.MaMonAn)=1");
			if (c != null) {
				NguyenLieu = new ArrayList<String>();
				if (c.moveToFirst()) {
					do {
						NguyenLieu.add(c.getString(c
								.getColumnIndex("TenNguyenLieu")));
					} while (c.moveToNext());
				}
			}
		} catch (Exception ex) {
		}
		dataAdapter.close(); // close conect database
	}
	
	// =================================================================================
	
	private void Query2(Bundle bundle) {
		DataFoodAdapter dataAdapter = new DataFoodAdapter(this);
		Cursor c;

		dataAdapter.OpenDataBase(); // open connect database

		try {
			c = dataAdapter.QueryData("Select * from MonAn where MaMonAn = '"
					+ bundle.getInt("Ma") + "'");
			if (c != null) {
				if (c.moveToFirst()) {
					do {
						GioiThieu = c.getString(c.getColumnIndex("GioiThieu"));
						NguyenLieuChuanBi = c.getString(c
								.getColumnIndex("NguyenLieuChuanBi"));
						ThucHien = c.getString(c.getColumnIndex("ThucHien"));
						blob = c.getBlob(c.getColumnIndex("HinhAnh"));						
						LoaiMonAn = c.getString(c.getColumnIndex("LoaiMonAn"));
						item = new StringInPair(c.getString(c
								.getColumnIndex("TenMonAn")), c.getInt(c
								.getColumnIndex("MaMonAn")));
						
					} while (c.moveToNext());
				}
			}
		} catch (Exception ex) {}
		dataAdapter.close(); // close conect database
		
	}
	
	// =================================================================================
	
	public BitmapDrawable convertBlobToBitmap(byte[] blobByteArray) {
		Bitmap tempBitmap = null;
		if (blobByteArray != null)
			tempBitmap = BitmapFactory.decodeByteArray(blobByteArray, 0,
					blobByteArray.length);
		int width = tempBitmap.getWidth();
		int height = tempBitmap.getHeight();

		Matrix matrix = new Matrix();
		float scaleWidth = ((float) 400) / width;
		float scaleHeight = ((float) 200) / height;
		matrix.postScale(scaleWidth, scaleHeight);
		matrix.postRotate(0); // rotate the Bitmap

		Bitmap resizingBitmap = Bitmap.createBitmap(tempBitmap, 0, 0, width,
				height, matrix, true); // recreate the new Bitmap

		BitmapDrawable bmd = new BitmapDrawable(resizingBitmap);

		return bmd;
	}
}
